//
//  P13MD5File.m
//  FindDuplicates
//
//  Created by Petur Ingi Egilsson on 8/15/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "P13MD5File.h"
#import <CommonCrypto/CommonDigest.h>

@implementation P13MD5File

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

+(NSString *) fileMD5:(NSString *)path
{
    NSFileHandle *fHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    NSString *md5string;
    if (fHandle == nil)
        return @"ERROR READING FILE";
    const NSUInteger BUFFER_SIZE = 1024;
    CC_MD5_CTX md5;
    CC_MD5_Init(&md5);
    BOOL done = NO;
    
    while (!done)
    {
        NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];
        NSData *fData = [fHandle readDataOfLength:BUFFER_SIZE];
        CC_MD5_Update(&md5, [fData bytes], (CC_LONG)[fData length]);
        if ([fData length] == 0)
            done = YES;
        [pool2 drain];
    }
    [fHandle closeFile];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &md5);
    md5string = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                 digest[0], digest[1], digest[2], digest[3], digest[4], digest[5],
                 digest[6], digest[7], digest[8], digest[9], digest[10], digest[11],
                 digest[12], digest[13], digest[14], digest[15]];
    return md5string;
}

@end
